const { sequelize } = require('../../core/db')
const { Sequelize, Model, Op } = require('sequelize')
const { Art } = require('@models/ArtModel')


class Favor extends Model {
  // 业务表

  // 主要负责用户的点赞和取消点赞的操作
  static async like(art_id, type, uid) {
    // 1.添加记录
    // 2 classic fav_nums
    // 数据库事物
    // 数据一致性
    const favor = await Favor.findOne({
      where: {
        art_id,
        type,
        uid,
      }
    })
    // 如果已经点过赞了
    if (favor) {
      throw new global.errs.linkError()
    }
    // 托管事物
    return sequelize.transaction(async (t) => {
      await Favor.create(
        {
          art_id,
          type,
          uid,
        },
        { transaction: t }
      )

      const art = await Art.getData(art_id, type, false)
      await art.increment('fav_nums', { by: 1, transaction: t }) // by即+1
    })
  }
  static async dislike(art_id, type, uid) {
    const favor = await Favor.findOne({
      where: {
        art_id,
        type,
        uid,
      },
    })
    // 如果未曾点赞
    if (!favor) {
      throw new global.errs.DislikeError()
    }
    return sequelize.transaction(async (t) => {
       // 软删除false，只会更改个标识表明已经被删除，硬性删除force:true则直接删除这条记录
      await favor.destroy({
        force: true,
        transaction: t,
      })

      const art = await Art.getData(art_id, type, false)
      await art.decrement('fav_nums', { by: 1, transaction: t })
    })
  }

  static async userLikeIt(art_id, type, uid) {
    const favor = await Favor.findOne({
        where: {
            art_id,
            type,
            uid
        }
    })
    return !!favor; // if(a!=null&&typeof(a)!=undefined&&a!='')
  }
  
  // 查询该用户下所有期刊的点赞列表
  static async getMyClassicFavors(uid) {
    const arts = await Favor.findAll({
      where: {
        uid,
        type: {
          [Op.not]: 400
        }
      }
    })
    if(!arts) {
      throw new global.errs.notFound()
    }
    
    // 批量ids按条件查询


    return arts
  }
}

/**
 * 点赞归类到模型上
 */

Favor.init(
  {
    uid: Sequelize.INTEGER, // 关联用户的id，可以知道谁点赞了
    art_id: Sequelize.INTEGER, // 点赞的是哪个期刊的id（实际上该id是相关类型的表的id）
    type: Sequelize.INTEGER, // 点赞的期刊属于什么类型
  },
  {
    sequelize,
    tableName: 'favor',
  }
)

module.exports = {
  Favor,
}
